package controller

import (
	"github.com/gin-gonic/gin"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_history/model"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_history/service"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/pkg/response"
)

func ExecJob(c *gin.Context) {
	var job model.JobDTO
	if err := c.ShouldBindJSON(&job); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}

	jobId, err := service.CreateJob(&job)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, gin.H{
		"job_id": jobId,
	}, "success")
}

func GetJobs(c *gin.Context) {
	query := &response.PagedQuery{}
	if err := c.ShouldBindQuery(query); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	jobType := c.Query("job_type")
	jobs, total, err := service.GetJobs(query, jobType)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.DataPaged(c, jobs, total, query)
}

func GetJobByJobId(c *gin.Context) {
	jobId := c.Param("job_id")
	job, err := service.GetJobByJobId(jobId)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, job, "success")
}

func GetJobResultByJobId(c *gin.Context) {
	jobId := c.Param("job_id")

	result, err := service.GetJobResultByJobId(jobId)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, result, "success")
}

func GetSubJobResultByJobId(c *gin.Context) {
	jobId := c.Param("job_id")
	ip := c.Param("ip")

	result, err := service.GetSubJobResultByJobId(jobId, ip)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, result, "success")
}

func ResumeManualJob(c *gin.Context) {
	var resumeReq model.TaskResumeRequest
	if err := c.ShouldBindJSON(&resumeReq); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}

	err := service.ResumeManualJob(&resumeReq)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}
